package org.hive.vmware.client.ui;

import java.util.ArrayList;
import java.util.List;

import org.hive.vmware.client.model.VmCenterServerVO;
import org.hive.vmware.client.service.CachedVmwareService;

import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CellEditor;
import com.extjs.gxt.ui.client.widget.grid.CellSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnData;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridCellRenderer;
import com.extjs.gxt.ui.client.widget.grid.GridSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.CellSelectionModel.CellSelection;
import com.extjs.gxt.ui.client.widget.grid.EditorGrid.ClicksToEdit;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FlowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ConfigurationPanel extends LayoutContainer {

	private final CachedVmwareService vmWareService = CachedVmwareService.getInstance();
	
	private ListStore<VmCenterServerVO> vmCenters;
	private EditorGrid<VmCenterServerVO> grid;
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		setLayout(new FlowLayout(10));

		List<ColumnConfig> configs = new ArrayList<ColumnConfig>();

		configs.add(createUrlColumn());
		configs.add(createUserIdColumn());
		configs.add(createPassword());

		vmCenters = new ListStore<VmCenterServerVO>();  
		
		ColumnModel cm = new ColumnModel(configs);
		
		grid = new EditorGrid<VmCenterServerVO>(vmCenters, cm);  
		grid.setBorders(true);
		grid.enableEvents(true);
		grid.setClicksToEdit(ClicksToEdit.TWO);
		
		ContentPanel cp = contentPanel();
		cp.setTopComponent(toolbar());
		cp.add(grid);
		addSaveActionButtons(cp);
		add(cp);
	}

	private void addSaveActionButtons(ContentPanel cp) {
		cp.setButtonAlign(HorizontalAlignment.CENTER);
		cp.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
			@Override
			public void componentSelected(ButtonEvent ce) {
				vmCenters.rejectChanges();
			}
		}));

		cp.addButton(new Button("Save", new SelectionListener<ButtonEvent>() {

			@Override
			public void componentSelected(ButtonEvent ce) {
				vmWareService.saveVmCenterServers(vmCenters.getModels(), new AsyncCallback<Boolean>(){

					@Override
					public void onFailure(Throwable caught) {
						Info.display("Save VMWare Server Centers", "Save VMware center server failed.");
					}
					
					@Override
					public void onSuccess(Boolean result) {
						loadModel();
						Info.display("Save VMWare Server Centers", "Successful.");
					}});
			}
		}));  
	}
	

	private ColumnConfig createUrlColumn() {
		ColumnConfig column = new ColumnConfig();
		column.setId("url");
		column.setHeader("Server Center Url");
		
		TextField<String> text = new TextField<String>();
		text.setAllowBlank(false);
		column.setEditor(new CellEditor(text));
		column.setWidth(430);
		return column;
	}

	private ColumnConfig createUserIdColumn() {
		ColumnConfig column = new ColumnConfig();
		TextField<String> text;
		column.setId("userId");
		column.setHeader("User Id");
		text = new TextField<String>();
		text.setAllowBlank(false);
		column.setEditor(new CellEditor(text));
		column.setWidth(110);
		return column;
	}
	
	private ColumnConfig createPassword() {
		ColumnConfig column = new ColumnConfig();
		TextField<String> text;
		column.setId("password");
		column.setHeader("Password");
		text = new TextField<String>();
		text.setPassword(true);
		text.setAllowBlank(false);
		column.setEditor(new CellEditor(text));
		column.setWidth(110);
		column.setRenderer(new GridCellRenderer<VmCenterServerVO>(){

			@Override
			public Object render(VmCenterServerVO model, String property,
					ColumnData config, int rowIndex, int colIndex,
					ListStore<VmCenterServerVO> store,
					Grid<VmCenterServerVO> grid) {
				return "**********";
			}});
		return column;
	}
	
	VmCenterServerVO create() {
		VmCenterServerVO vo = new VmCenterServerVO();
		vo.setUrl("https://sample.com/sdk");
		vo.setUserId("user-id");
		vo.setPassword("password");
		return vo;
	}
	
	ContentPanel contentPanel() {
		ContentPanel cp = new ContentPanel();  
		cp.setHeading("Edit VMware Center Server");  
		cp.setFrame(true);  
		cp.setSize(670, 300);  
		cp.setLayout(new FitLayout());
		return cp;
	}
	
	ToolBar toolbar() {
		ToolBar tb = new ToolBar();  
		Button add = new Button(" Add "); 
		add.addSelectionListener(new SelectionListener<ButtonEvent>(){
			@Override
			public void componentSelected(ButtonEvent ce) {
				grid.stopEditing();
				vmCenters.insert(create(),0);
				grid.startEditing(0, 0);
			}});
		
		Button delete = new Button(" Delete ");
		delete.addSelectionListener(new SelectionListener<ButtonEvent>(){
			@SuppressWarnings("unchecked")
			@Override
			public void componentSelected(ButtonEvent ce) {
				// so freak'n hard to determine a selected cell model!!
				GridSelectionModel<VmCenterServerVO> selectionModel = grid.getSelectionModel();
				CellSelectionModel<VmCenterServerVO> cellSelectionModel = (CellSelectionModel<VmCenterServerVO>)selectionModel;
				CellSelection selectCell = cellSelectionModel.getSelectCell();
				if (selectCell != null) {
					VmCenterServerVO vmCenterServerVO = (VmCenterServerVO)selectCell.model;
					grid.stopEditing();
					vmCenters.remove(vmCenterServerVO);
				}
			}});
		
		tb.add(add);
		tb.add(delete);
		return tb;
	}
	
	void loadModel() {
		vmWareService.loadVmCenterServers(new AsyncCallback<List<VmCenterServerVO>>(){
			@Override
			public void onFailure(Throwable caught) {
				Info.display("Load Error", "Error while loading VMware Center Servers.");
			}

			@Override
			public void onSuccess(List<VmCenterServerVO> vmCenterServerVOs) {
				vmCenters.removeAll();
				vmCenters.add(vmCenterServerVOs);
				grid.getSelectionModel().bind(vmCenters);
			}});
	}
}
